package Y2024.M12.D19;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-12-19
 * Time: 8:20
 */

public class client {
    public static void main(String[] args) {
        Socket socket = null;
        Scanner scanner = null;
        BufferedWriter writer = null;
        try {
            // 创建 Socket 并连接到 localhost 的 8080 端口
            socket = new Socket("localhost", 8080);
            // 输出已连接信息
            System.out.println("已连接");
            // 创建 Scanner 从控制台读取输入
            scanner = new Scanner(System.in);
            // 创建 BufferedWriter 向服务器发送数据
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String msg;
            // 循环发送消息
            while (!(msg = scanner.nextLine()).equals("bye")) {
                // 发送消息
                writer.write(msg);
                writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            try {
                if (writer!= null) {
                    writer.close();
                }
                if (scanner!= null) {
                    scanner.close();
                }
                if (socket!= null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
